package com.yida.admin;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.yida.bean.blogger;
import com.yida.service.serverblog;

@Controller
@RequestMapping("/admin")
public class login {

	@Autowired
	public serverblog service;
	
	@RequestMapping
	public String loginpage(HttpServletRequest request, Integer page) {
		 Cookie[] cookies = request.getCookies();
		 String username = "";
		 String password = "";
		 if (cookies!=null) {
			for (int i = 0; i < cookies.length; i++) {
				if ("username".equals(cookies[i].getName())) {
					username = cookies[i].getValue();		
				}
				if ("password".equals(cookies[i].getName())) {
					 password = cookies[i].getValue();
				}
			}
		 }
		  blogger blogger = service.selectBloggerservice(username, password);
		  if (blogger!=null) {
			  request.getSession().setAttribute("blogger", blogger);
			  return "redirect:/admin/blogs";
		}else {
			 return "admin/login";
		}
	
	}
	

	@RequestMapping("/login")
	public String login(String username, String password,HttpServletRequest request, HttpServletResponse response, RedirectAttributes attributes) {	 
		password = DigestUtils.md5DigestAsHex(password.getBytes());
	    blogger blogger = service.selectBloggerservice(username, password);
		    if (blogger!=null) {	  	
			        Cookie cookie1 = new Cookie("username", username);
			        Cookie cookie2 = new Cookie("password", password);
			        cookie1.setMaxAge(60*60*24*30*6);
			        cookie2.setMaxAge(60*60*24*30*6);
			        response.addCookie(cookie1);
			        response.addCookie(cookie2);
			   request.getSession().setAttribute("blogger", blogger);
			   return "redirect:/admin/blogs";
		}else {
			attributes.addFlashAttribute("message", "用户名或密码错误");
			return "redirect:/admin";
		}
		  
		  
		
	}
	  

	@RequestMapping("/logout")
	public String logout(HttpServletRequest request,HttpServletResponse response) {
		      request.getSession().removeAttribute("blogger");
		      Cookie cookie1 = new Cookie("username", "");
		      Cookie cookie2 = new Cookie("password", "");
		      cookie1.setMaxAge(0);
		      cookie2.setMaxAge(0);
		      response.addCookie(cookie1);
		      response.addCookie(cookie2);
              return "redirect:/admin";
	}
	
	
}
